package com.dagene.weixin.util;

import java.util.HashMap;
import java.util.Map;

public class TokenUtil {
	private static Map<String, String> tokenmap = new HashMap<String, String>();
	private static Map<String, String> ticketmap = new HashMap<String, String>();
	
	//防止AccessToken过期
	public static String getAccessToken() {
		long time = System.currentTimeMillis();
		if (!tokenmap.isEmpty()) {
			if ((time - Long.parseLong(tokenmap.get("expiresIn"))) / 1000 >= 7200 ) {
				//过期
				String tokeng = Util.getAccessToken();
				tokenmap.put("token", tokeng);
				tokenmap.put("expiresIn", Long.toString(time));
				return tokeng;
			} else {
				return tokenmap.get("token");
			}
		} else {
			String tokens = Util.getAccessToken();
			tokenmap.put("token", tokens);
			tokenmap.put("expiresIn", Long.toString(time));
			return tokens;
		}
	}
	
	//防止JsapiTicket过期
	public static String getJsapiTicket() throws Exception {
		long time = System.currentTimeMillis();
		if (!ticketmap.isEmpty()) {
			if ((time - Long.parseLong(ticketmap.get("expiresIn"))) / 1000 >= 7200 ) {
				//过期
				String ticketg = SignsUtil.getJsapiTicket();
				ticketmap.put("ticket", ticketg);
				ticketmap.put("expiresIn", Long.toString(time));
				return ticketg;
			} else {
				return ticketmap.get("ticket");
			}
		} else {
			String tickets = SignsUtil.getJsapiTicket();
			ticketmap.put("ticket", tickets);
			ticketmap.put("expiresIn", Long.toString(time));
			return tickets;
		}
	}
}
